; (function ($, window, document, undefined) {
  //fields配置说明 name:标题  field:对应的字段名称(当字段写MyIndex时为序号列)  isshowcheckall:表头是否显示全选框  isshowcheck:是否显示出选择框的方法(需要返回一个bool值)  ishide:该列是否隐藏的方法(需要返回一个bool值)  order:点击该列时按照该字段排序  formatter:返回内容的方法

  //定义Table的构造函数
  var TablePages = function (ele, opt) {
    this.$element = ele;
    this.defaults = {
      showScreen: true, //数据加载时是否显示遮罩层
      showMsg: '正在努力加载中',//数据加载时显示的信息
      keyField: '',//主键字段会保存在行tr的data属性里面
      orderField: '', // 排序字段
      orderType: '', // 排序  DESC 降序  ASC 升序
      orderLoad: true, //点击排序列 是否自动重新加载表格 为否的话会在左上角显示加载按钮
      orderMulti: false,//是否可以同时按照多个字段排序
      orderClick: function (orderField, orderType) {
        return;
      }, // 排序列点击事件
      fields: {}, // 列表列名及配置
      data: {},	// 列表数据
      checkedstatus: true,//是否允许多选
      url: '',  // 获取数据的地址
      param: {}, // 在使用URL时传递的参数 会自动加上页码、页面大小、排序字段、排序方式
      nodataafter: false,//没有数据时是否执行afterload方法
      afterLoad: function (json) {
        return;
      },//使用URL加载数据，加载完成后执行
      showPage: true,// 是否显示页码
      truePage: true,// 是真分页还是假分页（即是否是是数据库分页）
      pages: {
        pageIndex: 1, // 当前页码
        pageSize: 10, // 每页显示条数
        recordCount: 0, // 记录总数
        showPage: 0,	// 显示页码个数 为 0 则全部显示
        pageType: 'span', // 页码标签
        pageArea: 'center', // 页码地方  center居中  left 居左
        pageClick: function (pageindex) {
          return;
        }
      }
    };
    this.options = $.extend({}, this.defaults, opt);
    this.options.pages = $.extend({}, this.defaults.pages, opt.pages);
  }

  //定义Table的方法
  TablePages.prototype = {
    madeTable: function () {
      var $ele = this.$element;

      //设置元素样式
      $ele.css({ 'position': 'relative', 'text-align': 'center', 'width': '100%', 'height': '100%', 'overflow': 'hidden' });

      //移除上次的数据
      $ele.find('.tablebox').remove();
      $ele.find('.pagedivbox').remove();
      $ele.find('.yxytablepagesscreenbox').remove();
      $ele.find('.yxyreloadbtn').tooltip('destroy');
      $ele.find('.yxyreloadbtn').remove();

      //保存数据到data
      $ele.data('pageindex', parseInt(this.options.pages.pageIndex));
      $ele.data('orderfield', this.options.orderField);
      $ele.data('ordertype', this.options.orderType);

      //添加遮罩层
      if (this.options.showScreen) {
        $ele.append('<div class="yxytablepagesscreenbox"><span>' + this.options.showMsg + '</span></div>');
      }

      //添加重新加载按钮
      if (!this.options.orderLoad) {
        var optTemp = this.options;
        var reset = this.reSetTableOrder;
        $ele.append('<div class="yxyreloadbtn" title="重新加载" data-toggle="tooltip" data-placement="right" data-optype="read"><i class="glyphicon glyphicon-refresh"></i></div>')
        $ele.find('.yxyreloadbtn').tooltip();
        $ele.find('.yxyreloadbtn').eq(0).click(function () {
          optTemp.orderField = $ele.data('orderfield');
          optTemp.orderType = $ele.data('ordertype');
          reset($ele, optTemp);
        })
      }

      //数据列表
      var hei = $ele.parent().height();
      $ele.append('<div class="tablebox" style="overflow:auto;height:' + (hei - 42) + 'px;">' + this.createTable() + '</div>');
      this.tableOrder($ele, this.options);
      this.regTableOrderClick()
      $(window).resize(function () {
        var hei = $ele.parent().height();
        $ele.find('.tablebox').css('height', (hei - 42) + 'px');
      });

      //页码
      if (this.options.showPage) {
        $ele.append('<div class="pagedivbox" style="position:absolute;width:100%;bottom:-4px;">' + this.createPageHtml() + '</div>');
        this.regClick();

        if (this.options.pages.pageArea == 'left') {
          $ele.find('.pageulbox').eq(0).css({ 'float': 'left' });
        }

        if ($(window).width() < 800) {
          $ele.find('.pagedivbox').find('.first').hide();
          $ele.find('.pagedivbox').find('.last').hide();
        }
      }

      //设置全选 选择框改变事件
      $('input[name=chkAll]').on('click', function () {
        var m_list_checkbox = $("input[name='cid']");
        for (var i = m_list_checkbox.length - 1; i >= 0; i--) {
          m_list_checkbox[i].checked = $(this)[0].checked;
        }
      })

      //true为多选，false单选
      if (!this.options.checkedstatus) {
        $ele.find("input[type='checkbox']").click(function () {
          $ele.find("input[type='checkbox']").prop("checked", false);
          $(this).prop("checked", true);
        })
      }

      // 隐藏遮罩层
      this.hideScreen();
      return this;
    },
    tableOrder: function (obj, opt) {
      obj.find('.orderth').find('span').removeClass('on').removeClass('down');
      var fieldstemp = new Array();
      var orderstemp = new Array();
      if (opt.orderField.indexOf(',') > 0) {
        fieldstemp = opt.orderField.split(',');
      } else {
        fieldstemp.push(opt.orderField);
      }
      if (opt.orderType.indexOf(',') > 0) {
        orderstemp = opt.orderType.split(',');
      }
      else {
        orderstemp.push(opt.orderType);
      }
      for (var i = 0; i < fieldstemp.length; i++) {
        if (orderstemp.length > i && orderstemp[i] == 'DESC') {
          obj.find('.orderth[data-order="' + fieldstemp[i] + '"]').find("span").addClass("down");
        }
        else {
          obj.find('.orderth[data-order="' + fieldstemp[i] + '"]').find("span").addClass("on");
        }
      }
      return this;
    },
    regTableOrderClick: function () {
      var optTemp = this.options;
      var reset = this.reSetTableOrder;
      var $ele = this.$element;
      var orderclickTemp = this.options.orderClick;
      var tableorderTemp = this.tableOrder;
      // 排序列点击事件
      this.$element.find('th.orderth').on('click', function () {
        if (optTemp.orderMulti) {
          var fieldtemp = $(this).attr('data-order');
          var ordertemp = '';
          if ($(this).find('span.icon').hasClass('on')) {
            var ordertemp = 'DESC';
          }
          else if ($(this).find('span.icon').hasClass('down')) {
            ordertemp = '';
          }
          else {
            ordertemp = 'ASC';
          }
          // 之前的排序是空的
          if (optTemp.orderField.length <= 0) {
            if (ordertemp != '') {
              optTemp.orderField = fieldtemp;
              optTemp.orderType = ordertemp;
            }
          }
          // 之前只按照一个字段排序
          else if (optTemp.orderField.indexOf(',') <= 0) {
            // 之前的排序字段和点击字段一样
            if (optTemp.orderField == fieldtemp) {
              if (ordertemp == '') {
                optTemp.orderField = '';
                optTemp.orderType = '';
              }
              else {
                optTemp.orderType = ordertemp;
              }
            }
            else {
              optTemp.orderField += ',' + fieldtemp;
              optTemp.orderType += ',' + ordertemp;
            }
          }
          //之前按照多个字段排序
          else {
            var fileslist = new Array();
            fileslist = optTemp.orderField.split(',');
            var orderlist = new Array();
            orderlist = optTemp.orderType.split(',');
            var flag = 0;//标识之前的排序字段里是否还有点击字段
            for (var i = 0; i < fileslist.length; i++) {
              if (fileslist[i] == fieldtemp) {
                flag = 1;
                if (ordertemp == '') {
                  fileslist.splice(i, 1);
                  orderlist.splice(i, 1);
                }
                else {
                  orderlist[i] = ordertemp;
                }
              }
            }
            if (flag == 0) {
              if (ordertemp != '') {
                fileslist.push(fieldtemp);
                orderlist.push(ordertemp);
              }
            }
            optTemp.orderField = fileslist.join(',');
            optTemp.orderType = orderlist.join(',');
          }
        }
        else {
          if ($(this).find('span.icon').hasClass('down')) {
            optTemp.orderType = 'ASC';
          }
          else {
            optTemp.orderType = 'DESC';
          }
          optTemp.orderField = $(this).attr('data-order');
        }
        orderclickTemp(optTemp.orderField, optTemp.orderType);
        if (optTemp.orderLoad) {
          reset($ele, optTemp);
        }
        else {
          $ele.data('orderfield', optTemp.orderField);
          $ele.data('ordertype', optTemp.orderType);
          tableorderTemp($ele, optTemp);
        }
      });
      return this;
    },
    reSetTableOrder: function (obj, opt) {
      var tablepages = new TablePages(obj, opt);
      if (tablepages.options.url != '') {
        tablepages.MyAjax();
      }
      else {
        tablepages.madeTable();
      }
      return this;
    },
    jsonSort: function () {
      var mydata = this.options.data;
      var ordertype = this.options.orderType;
      var field = this.options.orderField;
      if (field == '') return mydata;
      for (var i = 0; i < mydata.length - 1; i++) {
        for (var j = 0; j < mydata.length - 1 - i; j++) {
          var a = mydata[j][field];
          var b = mydata[j + 1][field];
          var flag = 0;
          if (flag == 0 && this.checkDateTime(a) && this.checkDateTime(b)) {
            a = new Date(a);
            b = new Date(b);
            flag = 1;
          }
          if (flag == 0) {
            try {
              a = parseFloat(a);
              b = parseFloat(b);
              flag = 1;
            } catch (ex) { }
          }
          if (flag == 0) {
            try {
              a = parseInt(a);
              b = parseInt(b);
              flag = 1;
            } catch (ex) { }
          }
          if (ordertype == 'DESC') {
            if (a < b) {
              var temp = mydata[j + 1];
              mydata[j + 1] = mydata[j];
              mydata[j] = temp;
            }
          }
          else {
            if (a > b) {
              var temp = mydata[j + 1];
              mydata[j + 1] = mydata[j];
              mydata[j] = temp;
            }
          }

        }
      }
      return mydata;
    },
    //| 日期时间有效性检查 
    //| 格式为：YYYY-MM-DD HH:MM:SS 
    checkDateTime: function (str) {
      var reg = /(\d{1,4})[-/](\d{1,2})[-/](\d{1,2}) *(\d{1,2}):(\d{1,2}):(\d{1,2})\S*/;
      var r = str.toString().match(reg);
      if (r == null) return false;
      r[2] = r[2] - 1;
      var d = new Date(r[1], r[2], r[3], r[4], r[5], r[6]);
      if (d.getFullYear() != r[1]) return false;
      if (d.getMonth() != r[2]) return false;
      if (d.getDate() != r[3]) return false;
      if (d.getHours() != r[4]) return false;
      if (d.getMinutes() != r[5]) return false;
      if (d.getSeconds() != r[6]) return false;
      return true;
    },
    createTable: function () {
      var reHtml = '<table class="yxytable"><thead><tr>';
      for (var i = 0; i < this.options.fields.length; i++) {
        if (this.options.fields[i].ishide != null && this.options.fields[i].ishide != undefined) {
          if (this.options.fields[i].ishide()) {
            continue;
          }
        }
        if (this.options.fields[i].isshowcheckall != null && this.options.fields[i].isshowcheckall != undefined) {
          if (this.options.fields[i].isshowcheckall)
            reHtml += '<th><input type="checkbox" name="chkAll" /></th>';
          else
            reHtml += '<th></th>';
        }
        else if (this.options.fields[i].order != null && this.options.fields[i].order != '') {
          reHtml += '<th class="orderth" data-order="' + this.options.fields[i].order + '">' + this.options.fields[i].name + '<span class="icon"></span></th>';
        }
        else {
          reHtml += '<th>' + this.options.fields[i].name + '</th>';
        }
      }
      reHtml += '</tr></thead><tbody>';

      // 设置开始和结束索引
      var startIndex = 0;
      var endIndex = this.options.data.length;
      if (!this.options.truePage) {
        startIndex = (parseInt(this.options.pages.pageIndex) - 1) * parseInt(this.options.pages.pageSize);
        endIndex = parseInt(this.options.pages.pageIndex) * parseInt(this.options.pages.pageSize);
      }

      // 非真实分页实现排序
      if (!this.options.truePage) {
        this.options.data = this.jsonSort();
      }

      for (var i = startIndex; i < endIndex && i < this.options.data.length; i++) {
        var obj = this.options.data[i];
        if (this.options.keyField != null && this.options.keyField != undefined && this.options.keyField != '')
          reHtml += '<tr data-keyfield="' + obj[this.options.keyField] + '">';
        else
          reHtml += '<tr>';
        for (var j = 0; j < this.options.fields.length; j++) {
          if (this.options.fields[j].ishide != null && this.options.fields[j].ishide != undefined) {
            if (this.options.fields[j].ishide()) {
              continue;
            }
          }
          if (this.options.fields[j].formatter != null) {
            reHtml += '<td>' + this.options.fields[j].formatter(obj) + '</td>';
          }
          else if (this.options.fields[j].isshowcheckall != null && this.options.fields[j].isshowcheckall != undefined) {
            if (this.options.fields[j].isshowcheck == null || this.options.fields[j].isshowcheck(obj))
              reHtml += '<td><input name="cid" type="checkbox" value="' + obj[this.options.fields[j].field] + '"/></td>';
            else
              reHtml += '<td></td>';
          }
          else if (this.options.fields[j].field == 'MyIndex') {
            if (this.options.truePage) {
              reHtml += '<td>' + ((parseInt(this.options.pages.pageIndex) - 1) * parseInt(this.options.pages.pageSize) + i + 1) + '</td>';
            }
            else {
              reHtml += '<td>' + (i + 1) + '</td>';
            }
          }
          else {
            reHtml += '<td>' + (obj[this.options.fields[j].field] == null ? '-' : obj[this.options.fields[j].field]) + '</td>';
          }
        }
        reHtml += '</tr>';
      }
      if (this.options.data.length == 0) {
        reHtml += '<tr><td colspan="' + this.options.fields.length + '">未查到符合条件的记录</td></tr>'
      }
      reHtml += '</tbody></table>'
      return reHtml;
    },
    createPageHtml: function () {
      var pageindextemp = parseInt(this.options.pages.pageIndex);
      var pagesizetemp = parseInt(this.options.pages.pageSize);
      var recordcounttemp = parseInt(this.options.pages.recordCount);
      var showpagetemp = parseInt(this.options.pages.showPage);

      var pageCount = parseInt((recordcounttemp + pagesizetemp - 1) / pagesizetemp);
      var sb = "";
      if (pageCount >= 2) {
        sb += '<ul class="pageulbox"><li class="disabled"><' + this.options.pages.pageType + '>共' + pageCount + '页,' + recordcounttemp + '条</' + this.options.pages.pageType + '></li>'
        if (pageindextemp == 1) {
          sb += '<li class="disabled"><' + this.options.pages.pageType + ' data-page="1" class="first">首页</' + this.options.pages.pageType + '></li>';
          sb += '<li class="disabled"><' + this.options.pages.pageType + ' data-page="' + (pageindextemp - 1) + '">上一页</' + this.options.pages.pageType + '></li>';
        }
        else {
          sb += '<li class="normal"><' + this.options.pages.pageType + ' data-page="1" class="first">首页</' + this.options.pages.pageType + '></li>';
          sb += '<li class="normal"><' + this.options.pages.pageType + ' data-page="' + (pageindextemp - 1) + '">上一页</' + this.options.pages.pageType + '></li>';
        }

        var startPage = 1;
        var endPage = pageCount;
        if (showpagetemp > 0) {
          //计算开始结束页码
          startPage = pageindextemp - parseInt(showpagetemp / 2);
          startPage = startPage < 1 ? 1 : startPage;
          endPage = startPage + showpagetemp - 1;
          endPage = endPage > pageCount ? pageCount : endPage;
          startPage = (endPage - showpagetemp + 1) < 1 ? 1 : (endPage - showpagetemp + 1);
        }

        for (var i = startPage; i <= endPage; i++) {
          if (i == pageindextemp) {
            sb += '<li class="active"><' + this.options.pages.pageType + ' data-page="' + i + '">' + i + '</' + this.options.pages.pageType + '></li>';
          }
          else {
            sb += '<li class="normal"><' + this.options.pages.pageType + ' data-page="' + i + '">' + i + '</' + this.options.pages.pageType + '></li>';
          }
        }

        if (pageindextemp == pageCount) {
          sb += '<li class="disabled"><' + this.options.pages.pageType + ' data-page="' + (pageindextemp + 1) + '">下一页</' + this.options.pages.pageType + '></li>';
          sb += '<li class="disabled"><' + this.options.pages.pageType + ' data-page="' + pageCount + '" class="last">末页</' + this.options.pages.pageType + '></li>';
        }
        else {
          sb += '<li class="normal"><' + this.options.pages.pageType + ' data-page="' + (pageindextemp + 1) + '">下一页</' + this.options.pages.pageType + '></li>';
          sb += '<li class="normal"><' + this.options.pages.pageType + ' data-page="' + pageCount + '" class="last">末页</' + this.options.pages.pageType + '></li>';
        }
        sb += '</ul>';
      }
      return sb;
    },
    regClick: function () {
      var clientfun = this.options.pages.pageClick;
      var reset = this.reSetPage;
      var ops = this.options;
      var $ele = this.$element;

      $ele.find('.pageulbox > li[class^=normal] > a,.pageulbox > li[class^=normal] > span').on('click', function () {
        var pageindex = parseInt($(this).attr('data-page'));
        clientfun(pageindex);
        ops.pages.pageIndex = pageindex;
        reset($ele, ops);
      });
      return this;
    },
    reSetPage: function (obj, opt) {
      var tablepages = new TablePages(obj, opt);
      if (tablepages.options.url != '') {
        tablepages.MyAjax();
      }
      else {
        tablepages.madeTable();
      }
      return this;
    },
    hideScreen: function () {
      this.$element.find('.yxytablepagesscreenbox').hide();
    },
    showScreen: function () {
      this.$element.find('.yxytablepagesscreenbox').show();
    },
    showMessage: function (type, msg, time, url, obj) {
      var $myeletemp = $(obj);
      if (type == 0) {
        $myeletemp.find('.yxytablemessage').eq(0).addClass('success');
      }
      else {
        $myeletemp.find('.yxytablemessage').eq(0).addClass('error');
      }
      $myeletemp.find('.yxytablemessage').eq(0).html(msg).show();
      setTimeout(function () {
        $myeletemp.find('.yxytablemessage').eq(0).hide();
        if (url != '') {
          var urlNow = location.href;
          location.href = url + '?resultUrl=' + urlNow;
        }
      }, time * 1000);
    },
    // 通过url获取数据
    MyAjax: function () {
      //显示遮罩层
      this.showScreen();

      var hidesc = this.hideScreen;
      var smsg = this.showMessage;

      //定义对象的属性备份 在ajax后调用时要用到
      var opt = this.options;
      var $ele = this.$element;

      var afload = opt.afterLoad;

      //设置参数
      opt.param.pageIndex = opt.pages.pageIndex;
      opt.param.pageSize = opt.pages.pageSize;
      opt.param.orderFiled = opt.orderField;
      opt.param.orderType = opt.orderType;

      //将参数转换成JSON字符串
      var temp = JSON.stringify({ jsoncs: JSON.stringify(opt.param) });

      $.ajax({
        type: "POST",
        url: this.options.url,
        data: temp,
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        async: true,//异步     
        success: function (json) {
          //返回的结果要为 {"list":{"rows":[{...},{...}],"total":100},"s":0,"m":"显示消息","u":"需要跳转的URL"}  s  0正常  1 错误
          //或者{"list":[{...},{...}],recordcount:100,"s":0,"m":"显示消息","u":"需要跳转的URL"}
          if (json.s != null) {
            //添加错误正确显示框
            $ele.find('.yxytablemessage').remove();
            $ele.append('<div class="yxytablemessage"></div>');

            if (json.s != 0)
              smsg(json.s, json.m, 2, json.u, $ele);

            if (json.s != 0)
              return;
          }

          //结果序列化
          var result = eval('(' + json.list + ')')
          //设置数据
          if (result.rows != null && typeof (result.rows) != undefined) {
            opt.data = result.rows;
            //设置记录条数
            opt.pages.recordCount = result.total;
          }
          else {
            opt.data = result;
            //设置记录条数
            opt.pages.recordCount = json.recordcount;
          }

          var tablepages = new TablePages($ele, opt);
          tablepages.madeTable();
          if (opt.nodataafter || opt.pages.recordCount>0)
            afload(json);
        }, error: function () {
          console.log('网络错误【' + this.url + '】！');
          hidesc();
        }
      })
    }

  }

  //初始化方法
  $.fn.yxyTablePages = function (options) {
    var tablepages = new TablePages(this, options);
    if (tablepages.options.url != '') {
      tablepages.MyAjax();
    }
    else {
      tablepages.madeTable();
    }
    return this;
  }

  //获取选中的列的值 用逗号隔开
  $.fn.yxyTableGetallCheckID = function () {
    var allcid = '';
    var e = $(this).find('table.yxytable').eq(0).find("input[name='cid']");
    for (var i = 0; i < e.length; i++) {
      if (e[i].type == "checkbox") {
        if (e[i].checked == true) {
          allcid += e[i].value + ',';
        }
      }
    }
    return allcid.substring(0, allcid.length - 1);
  }

  //获取当前页码
  $.fn.yxyTableGetPageIndex = function () {
    var $this = $(this);
    var pageindex = $this.data('pageindex');
    if (typeof (pageindex) == 'undefined') {
      pageindex = $this.find('ul.pageulbox').eq(0).find('li.active').eq(0).find('span,a').eq(0).attr('data-page');
      if (!pageindex)
        pageindex = 0;
      $this.data('pageindex', pageindex);
    }
    return pageindex;
  }

  //获取排序字段
  $.fn.yxyTableGetOrderField = function () {
    var $this = $(this);
    var orderfield = $this.data('orderfield');
    if (typeof (orderfield) == 'undefined') {
      orderfield = $this.find('table.yxytable>thead>tr>th.orderth').find('span.on,span.down').eq(0).parent().attr('data-order');
      if (!orderfield)
        orderfield = '';
      $this.data('orderfield', orderfield);
    }
    return orderfield;
  }

  //获取排序类型
  $.fn.yxyTableGetOrderType = function () {
    var $this = $(this);
    var ordertype = $this.data('ordertype');
    if (typeof (ordertype) == 'undefined') {
      var onCount = $this.find('table.yxytable>thead>tr>th.orderth').find('span.on').length;
      if (onCount > 0) ordertype = 1;

      var downCount = $this.find('table.yxytable>thead>tr>th.orderth').find('span.down').length;
      if (downCount > 0) ordertype = 0;

      $this.data('ordertype', ordertype);
    }
    return ordertype;
  }
})(jQuery, window, document);